/*
 * @Author: xiaosihan
 * @Date: 2024-07-30 23:55:38
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-09-01 12:23:47
 */

import { configure, observable } from "mobx";
import { UploadAttachment } from "./type";
import utils from "@utils";
import numeral from "numeral";
import utilsApi from "@api/utilsApi";
import partsApi from "@api/partsApi";
import { get } from "lodash";

configure({ enforceActions: "never" });

const uploadProgressModalStore = observable(
  {
    // 上传完成后的零件id
    modelId: "",
    setModelId(modelId: string = "") {
      this.modelId = modelId;
    },

    // 格式转换中
    formmatConrt: false,
    setFormmatConrt(formmatConrt: boolean) {
      this.formmatConrt = formmatConrt;
    },

    // 打开弹窗
    open: false,
    setOpen(open: boolean) {
      this.open = open;
      this.setProgress(0);
    },

    //进度
    progress: 0,
    setProgress(progress: number) {
      this.progress = progress;
    },

    // 上传的文件名
    fileName: "",
    setFileName(fileName: string) {
      this.fileName = fileName;
    },

    //上传文件的附加列表
    uploadAttachmentList: [] as Array<UploadAttachment>,
    setUploadAttachmentList(uploadAttachmentList: Array<UploadAttachment>) {
      this.uploadAttachmentList = uploadAttachmentList;
    },
    async addUploadAttachmentList(files: Array<File>) {
      const uploadAttachments: Array<UploadAttachment> = files.map((file) => {
        return {
          id: utils.uuid(),
          file: file,
          name: file.name,
          size: numeral(file.size).format("0.0b"),
          uploadProgress: 0,
        };
      });

      this.uploadAttachmentList = [
        ...this.uploadAttachmentList,
        ...uploadAttachments,
      ];

      // 开始上传
      for (let i = 0; i < uploadAttachments.length; i++) {
        const u = uploadAttachments[i];
        const url = await utilsApi.uploadOss(u.file, (progress) => {
          uploadProgressModalStore.updateUploadProgress(u.id, progress);
        });
        uploadProgressModalStore.updateUploadProgress(u.id, 1);
        const res = await partsApi.addAttachment({
          modelId: this.modelId,
          name: u.name,
          url: url,
          size: u.size,
        });
        const id = get(res, ["data", "id"]);
        u.id = id;
      }
    },
    //更新上传进度
    updateUploadProgress(id: string, uploadProgress: number) {
      this.uploadAttachmentList = [
        ...this.uploadAttachmentList.map((u) => {
          if (u.id === id) {
            u.uploadProgress = uploadProgress;
          }
          return u;
        }),
      ];
    },
    //删除附件
    deleteAttachment(id: string) {
      this.uploadAttachmentList = [
        ...this.uploadAttachmentList.filter((u) => u.id !== id),
      ];
      partsApi.deleteAttachment(id);
    },
  },
  {},
  { deep: false }
);

export default uploadProgressModalStore;
